package cn.eonshine.cuba.lsms.modular.basic.service.impl;

import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.eonshine.cuba.inf.common.util.DateUtils;
import cn.eonshine.cuba.inf.common.http.InfStatus;
import cn.eonshine.cuba.inf.modular.basic.entity.Pipeline;
import cn.eonshine.cuba.lsms.modular.CommonService;
import cn.eonshine.cuba.lsms.modular.basic.entity.BPipline;
import cn.eonshine.cuba.lsms.modular.basic.service.IBPiplineService;
import cn.eonshine.cuba.lsms.modular.basic.service.IBpiplineClientService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;

@Service
public class BpiplineClientService extends CommonService<Pipeline> implements IBpiplineClientService{
	
	@Autowired
	private IBPiplineService iBPiplineService;

	private final String listUrl = "/pipeline/list";
	private final String updateUrl = "/pipeline/update";
	@Override
	public void requestPipline() {
		requestData(listUrl, updateUrl);
	}

	@Override
	protected Object dataHandle(Pipeline pipeline) throws Exception {
		QueryWrapper<BPipline> entity = new QueryWrapper<BPipline>();
		entity.eq("code", pipeline.getCode());
		BPipline info = iBPiplineService.getOne(entity);
		boolean isInsert = false;
		if(info == null) {
			info = new BPipline();
			isInsert = true;
		}
		
//		info.setCode(pipeline.getCode());
//		info.setName(pipeline.getName());
//		info.setPiplineLength(pipeline.getPiplineLength());
//		info.setPiplineDiameter(piplineDiameter);
		
		BeanUtil.copyProperties(pipeline, info,true, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
		
		info.setCreateBy(InfStatus.CREATE_BY);
		if(info.getCreateDate() == null) {
			info.setCreateDate(DateUtils.getCubaDate(Calendar.getInstance().getTime()));
		}
		info.setUpdateBy(InfStatus.UPDATE_BY);
		if(info.getUpdateDate() == null) {
			info.setUpdateDate(DateUtils.getCubaDate(Calendar.getInstance().getTime()));
		}
		
		if(isInsert) {
			iBPiplineService.save(info);
		}else {
			iBPiplineService.updateById(info);
		}
		
		return info;
	}

	@Override
	protected List<Pipeline> feadBackDataHandle(Object obj, Pipeline pipeline, List<Pipeline> feadBackDataLists)
			throws Exception {
		BPipline info = (BPipline) obj;
		Pipeline tmpBack = new Pipeline();
		tmpBack.setId(info.getId());
		tmpBack.setCode(pipeline.getCode());
		tmpBack.setDataInputDatetime(pipeline.getDataInputDatetime());
		tmpBack.setLsmsUpdate(InfStatus.LSMS_UPDATE_EXTRACT_YES);
		tmpBack.setName(StringUtils.trim(info.getName()));
		feadBackDataLists.add(tmpBack);
		return feadBackDataLists;
	}
}
